package com.lagou.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Server {
	public static void main(String[] args) {
		try {
			RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
			CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
			.connectString("47.113.125.191:2181")
			.sessionTimeoutMs(50000)
			.connectionTimeoutMs(30000)
			.retryPolicy(retryPolicy)
			.namespace("servers")
			.build();
			curatorFramework.start();
			CuratorCache curatorCache = CuratorCache.builder(curatorFramework, "/").build();
			CuratorCacheListener curatorCacheListener = CuratorCacheListener.builder().forPathChildrenCache("/servers", curatorFramework, new PathChildrenCacheListener() {
				@Override
				public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
					Type type = pathChildrenCacheEvent.getType();
					// ChildData childData = pathChildrenCacheEvent.getData();
					// byte[] bytes = childData.getData();
					// String str = new String(bytes);
					System.out.println("type:" + type);
					// System.out.println("str:" + str);
					/*
					switch (type) {
					case INITIALIZED:
						break;
					case CHILD_ADDED:
						break;
					case CHILD_UPDATED:
						break;
					case CHILD_REMOVED:
						break;
					default:
						break;
					}
					*/
				}
			}).build();
			curatorCache.listenable().addListener(curatorCacheListener);
			curatorCache.start();
			Thread.sleep(Integer.MAX_VALUE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

